import React, { useState } from 'react';
import { Modal } from 'antd';

/**
 * 异步关闭的模态框
 *
 * @typedef ModalAsyncProps
 * @property {function(boolean): void} setVisible 用于关闭模态框,
 * @property {function(function)} [ok] 模态框onOk执行的函数，返回fasle不关闭模态框,
 * @property {React.ReactNode} [props.children]
 * @property {function(function): React.ReactNode} [generateContent] (setLoading) => ReactNode,
 *
 * @param {ModalAsyncProps & import('antd').ModalProps} props
 * @param {function(boolean): void} props.setVisible 用于关闭模态框,
 * @param {function(function)} [props.ok] 模态框onOk执行的函数，返回fasle不关闭模态框,
 * @param {React.ReactNode} [props.children]
 * @param {function(function): React.ReactNode} [props.generateContent] (setLoading) => ReactNode,
 */
interface ModalAsyncProps {
    setVisible: (visible: boolean) => void;
    ok: () => void;
    children: React.ReactNode;
    generateContent: () => React.ReactNode;
    // 其他 modalProps 类型声明
}

const ModalAsync: React.FC<ModalAsyncProps & any> = ({ setVisible, ok, children, generateContent, ...modalProps }) => {

    const [loading, setLoading] = useState(false);

    const close = () => {
        setLoading(false);
        setVisible(false);
    };

    const handleOk = async () => {
        if (ok) {
            setLoading(true);
            await Promise.resolve(ok(setLoading))
                .then((res) => {
                    // 返回true关闭模态框
                    if (typeof res === 'boolean') {
                        setLoading(false);
                        setVisible(!res);
                    }
                })
                .catch(() => setLoading(false));
        } else {
            close();
        }
    };

    return (
        <Modal
            onOk={handleOk}
            confirmLoading={loading}
            onCancel={close}
            destroyOnClose
            centered
            {...modalProps}
        >
            {children || generateContent?.(setLoading)}
        </Modal>
    );
};

export default ModalAsync;
